package cn.xd.base.domain.entity;

import cn.xd.base.basic.enums.DictKeyTypeEnum;
import cn.xd.base.basic.type.*;
import cn.xd.base.domain.bean.command.AddDictCommand;
import cn.xd.base.domain.bean.command.UpdateDictCommand;
import cn.xd.common.exception.BizException;
import cn.xd.core.ddd.entity.Entity;
import lombok.Data;

import java.util.Date;


/**
 * @author : mirzaLin
 * @data : 2023/11/20
 * @description : 字典
 **/
@Data
public class Dict implements Entity<DictId> {
    private DictId id;
    /**
     * 字典分组id
     */
    private DictGroupId groupId;
    /**
     * 字典名称
     */
    private DictName name;
    /**
     * 字典编码
     */
    private DictCode code;
    /**
     * 备注
     */
    private Remark remark;
    private AutoDictKey autoDictKey;
    private DictKeyType dictKeyType;

    private UserId creatorId;

    private TimeValue createTime;

    private UserId updaterId;

    private TimeValue updateTime;

    /**
     * 新增字典
     *
     * @param command 新增字典内容
     * @param userId  操作用户id
     * @return 新增字典实体
     */
    public static Dict add(AddDictCommand command, Long userId) {
        Date now = new Date();
        Dict dict = new Dict();
        dict.groupId = DictGroupId.of(command.getGroupId());
        dict.name = DictName.of(command.getName());
        dict.code = DictCode.of(command.getCode());
        dict.remark = Remark.of(command.getRemark());
        dict.autoDictKey = AutoDictKey.of(command.getAutoDictKey());
        dict.dictKeyType = DictKeyType.of(command.getDictKeyType());
        dict.creatorId = UserId.of(userId);
        dict.createTime = TimeValue.of(now);
        dict.updaterId = UserId.of(userId);
        dict.updateTime = TimeValue.of(now);
        return dict;
    }

    /**
     * 更新字典
     *
     * @param command 更新字典内容
     * @param userId  操作用户id
     */
    public void update(UpdateDictCommand command, Long userId) {
        this.groupId = DictGroupId.of(command.getGroupId());
        this.name = DictName.of(command.getName());
        this.code = DictCode.of(command.getCode());
        this.remark = Remark.of(command.getRemark());
        this.dictKeyType = DictKeyType.of(command.getDictKeyType());
        this.updaterId = UserId.of(userId);
        this.updateTime = TimeValue.now();
    }

    public void check(String dictKey) {
        if (DictKeyTypeEnum.INT.getCode().equals(this.getDictKeyType().getValue())) {
            try {
                int i = Integer.parseInt(dictKey);
            } catch (Exception ex) {
                throw new BizException("字典配置内容应该为整形类型:" + dictKey);
            }
        }
        if (DictKeyTypeEnum.LONG.getCode().equals(this.getDictKeyType().getValue())) {
            try {
                long l = Long.parseLong(dictKey);
            } catch (Exception ex) {
                throw new BizException("字典配置内容应该为长整形类型:" + dictKey);
            }
        }
    }
}
